package artid.com.arttogoa.fragment;

import java.util.ArrayList;
import java.util.List;
import artid.com.arttogoa.MySellInfo_Activity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.adapter.MySell_Adapter;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.MySellParser;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullToRefreshLayout;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullableListView;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullToRefreshLayout.OnRefreshListener;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 *
 * 项目名称：ArtworkArtA   
 * 类名称   ：MySell_Fragment   
 * 类描述   ：我出售的  Fragment   
 * 创建人   ：耿卫斌   
 * 创建时间：2016-7-15 上午11:07:08   
 *
 */
public class MySell_Fragment extends Fragment implements OnClickListener{
	private View v;
	private Context mContext;
	private PullableListView mListView;
	private PullToRefreshLayout mPullLayout;
	private boolean isRefreshed = false;// 是否刷新
	private int page=1;
	private int whichActivity=0;//默认出售中(0:出售中 1：已下架 )
	private MySell_Adapter adapter;
	private List<MySellParser> list;
	private List<MySellParser> more_list;
	private LinearLayout noDataLL;
	private TextView noDataHint;

	public View onCreateView(LayoutInflater inflater,
							 @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v=inflater.inflate(R.layout.fragment_onsale, null);
		initView();
		return v;
	}

	public MySell_Fragment(int whichActivity) {
		super();
		this.whichActivity = whichActivity;
	}

	private void initView(){
		mContext=getActivity();
		list=new ArrayList<MySellParser>();
		more_list=new ArrayList<MySellParser>();
		//注册当前广播
		IntentFilter filter = new IntentFilter("com.MySell_fragment.receiver");
		mContext.registerReceiver(broadcastReceiver, filter);
		noDataLL=(LinearLayout) v.findViewById(R.id.include_noDataLL);
		noDataHint=(TextView) v.findViewById(R.id.include_noData_hint);
		mListView =(PullableListView) v.findViewById(R.id.onsale_listivew);
		mPullLayout = (PullToRefreshLayout)v.findViewById(R.id.onsale_refresh_view);
		if(whichActivity==0){
			noDataHint.setText("哎呦，没有出售中的物品哦！");
		}else{
			noDataHint.setText("哎呦，没有已下架的物品哦！");
		}
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
									long arg3) {
				// TODO Auto-generated method stub
				Intent i=new Intent(mContext,MySellInfo_Activity.class);
				i.putExtra("whichActivity", whichActivity);
				i.putExtra("goods_id", more_list.get(position).getGoods_id());
				i.putExtra("goods_position", position);
				startActivity(i);
			}
		});
		mPullLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				//下拉刷新
				page=1;
				isRefreshed=true;
				getArtistgoodsList();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				// pullToRefreshLayout.setBottomDismiss();
				//上拉加载
				page++;
				getArtistgoodsList();
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	/**
	 * 获取我出售的列表
	 */
	private void getArtistgoodsList(){
		String state="1";//默认出售中
		if(whichActivity==0){
			//出售中
			state="1";
		}else if(whichActivity==1){
			//已下架
			state="0";
		}
		VolleyBasic.getInstance(getActivity()).post(true,false,Cache.artistgoodsList,
				VolleyMap.getInstance().artistgoodsList(state, page,5),
				MySellParser.class, new VolleyCallback() {

					@SuppressWarnings("unchecked")
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						VolleyBasic.disMissLoding();
						System.out.println(vd.getJson());
						if (page == 1) {
							//当请求第二页的时候num不会返回值
							try {
								JSONObject obj = new JSONObject(vd.getJson());
								String num = obj.optString("num");
								if(!StringUtils.isEmpty(num)) {
									AppUtil.getUser().setGoodsnum(num);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
						mPullLayout.loadmoreFinish(mPullLayout.SUCCEED);
						list=(List<MySellParser>) vd.getList();
						if (isRefreshed == true) {
							more_list.clear();
							isRefreshed = false;
						}
						if (!list.isEmpty()) {
							more_list.addAll(list);
						}
						if(more_list!=null && more_list.size()!=0){
							noDataLL.setVisibility(View.GONE);
						}else{
							noDataLL.setVisibility(View.VISIBLE);
							return;
						}
						if (adapter == null) {
							adapter=new MySell_Adapter(getActivity(),more_list,whichActivity);
							mListView.setAdapter(adapter);
						}
						adapter.notifyDataSetChanged();
					}
					public void onError(VolleyError volleyError) {
						mPullLayout.loadmoreFinish(mPullLayout.FAIL);
						VolleyBasic.disMissLoding();
						if(more_list!=null && more_list.size()!=0){
							noDataLL.setVisibility(View.GONE);
						}else{
							noDataLL.setVisibility(View.VISIBLE);
							return;
						}
					}
				});
	}

	/**
	 * 广播接收器
	 */
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String intentActivity=intent.getStringExtra("intentActivity");
			if(("我出售的详情"+whichActivity+"-删除").equals(intentActivity)){
				int goods_position=intent.getIntExtra("goods_position", -1);
				if(goods_position!=-1 && more_list!=null && more_list.size()!=0){
					more_list.remove(goods_position);
					adapter.notifyDataSetChanged();
					if(more_list==null || more_list.size()==0){
						noDataLL.setVisibility(View.VISIBLE);
					}
				}
			}else if("我出售的已下架-删除".equals(intentActivity)){
				noDataLL.setVisibility(View.VISIBLE);
			}else if(("我出售的详情-编辑").equals(intentActivity) || "艺术品出售".equals(intentActivity)){
				page=1;
				isRefreshed=true;
				getArtistgoodsList();
			}
		}
	};

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		//销毁广播
		mContext.unregisterReceiver(broadcastReceiver);
	}

	/**
	 * 防止控件没加载出来报空
	 */
	private void getDatas(){
		if(v!=null){
			page=1;
			isRefreshed=true;
			adapter=null;
			getArtistgoodsList();
		}else{
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					if(v!=null){
						getDatas();
					}
				}
			}, 1000);
		}
	}

	/**
	 * 每次切换Fragment刷新页面
	 */
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		super.setUserVisibleHint(isVisibleToUser);
		// 每次切换fragment时调用的方法
		if (isVisibleToUser) {
			getDatas();
		}
	}
}
